Energizing Change: Electric Vehicle Rise in Switzerland
Author
Pierre Vernet, Alexis Jeanneret, Hugo Troendle, Urs Hurni
Published
December 4, 2023
1 Introduction
1.1 Background and Motivation
In an era marked by unprecedented environmental challenges, our world is at a critical juncture where sustainable practices are no longer an option but a necessity. Climate change, driven by anthropogenic activities, poses an imminent threat to the delicate ecological balance. Recognizing the urgency of this global issue, we are compelled to investigate the specific context of Switzerland, the country we live in, and which has a lot of financial capacities to change rapidly.
The automotive sector plays a pivotal role in shaping the a sustainable world, and our focus on electric vehicle adoption in Switzerland reflects a strategic choice to comprehend the intricate interplay of factors driving this transition.
The motivations underlying our research stem from a multifaceted perspective. Firstly, the automotive industry is undergoing a transformative shift globally, with electric vehicles emerging as a key solution to reduce carbon emissions. By narrowing our focus to Switzerland, we aim to provide nuanced insights into the factors influencing EV adoption, offering a unique perspective on the socio-economic, environmentally stable and financially comfortable Swiss context. The adoption of electric vehicles provides an insight into people’s inclination to make efforts towards sustainability. This emphasizes the crucial role that electric vehicle adoption plays in evaluating society’s commitment to sustainable practices.
Secondly, our commitment to environmental sustainability extends beyond a generic interest. The urgency of addressing climate change has never been more palpable, and our research seeks to contribute to the discussion on sustainable mobility.
Moreover, we believe the future is encapsulated in our dedication to understanding the dynamics of environmentally conscious consumer behavior. By unraveling the complexities of EV adoption in Switzerland over the years (2005-2022), we aim to offer valuable insights that could guide policymakers, businesses, and consumers towards more informed and sustainable choices.
We believe that by comprehensively analyzing the impact of external factors on the adoption of electric vehicles in Switzerland, we can contribute meaningfully to the ongoing global efforts towards a more sustainable and resilient future. Through this project, we aspire to inspire positive change, foster innovation, and advocate for a paradigm shift towards eco-friendly practices in the automotive sector and beyond.
The initial source contains a comprehensive overview of electric vehicles (EVs) in Switzerland, which gave us further incentive to dive deeper into the topic.The second article presents essential statistical data relating to publicly accessible recharging infrastructure for electric mobility in Switzerland.
1.3 Reseach Questions
Given fluctuations in oil prices, demographic shifts, and major policy, which of these factors have a direct causal impact on the shifts in the adoption of electric vehicles in Switzerland?
Based on past electric vehicle adoption trends in Switzerland, can we forecast future adoption rates and pinpoint times of significant increases or decreases correlated with major events or policy changes?
In comparing regions in Switzerland, which areas show higher or lower adoption of electric vehicles, and how does this regional adoption align or vary with external factors like oil price changes, political opinions, and demographic shifts?
How has the growth of electric vehicles evolved in comparison to other countries such as France, and what factors might account for the differences in their evolution ?
To what extent does the evolution in the availability of charging stations exert an influence on the adoption of electric vehicles in Switzerland?
2 Data
2.1 Raw Datasets
Use a Loop for Similar Files.
Check for Large Data: If any of our datasets are particularly large (like the swiss_vehicle), we used a more efficient data reading librariy data.table (with fread) to speed up the data loading process.
We also added a common file path prefix (“../data/”) to make the code cleaner and easier to change for any usage in the future.
For this phase of the project, our approach involves presenting diverse datasets in a table form. To achieve this, we used the kable function from the kableExtra package, resulting in a table that displays each variable along with its corresponding definition and also added some bootstrap_otions for different stlyles.
2.1.1 Swiss Vehicle Registration Dataset
This data set explains the new registrations of road vehicles by vehicle group, canton, vehicle type, fuel, month and year in Switzerland. This data set is essential to evaluate the EVs’ evolution within our chosen location.
Code
# Create a tibble with variable descriptionsvariable_table_vehicle <-tibble(Variable =c("Canton", "Vehicle Group / Type", "Fuel", "Month", "2009-2022"),Description =c("The region in Switzerland.","Type or group of the vehicle.","Type of fuel used by the vehicle.","The month of the data.","Number of vehicles for each respective year. Each with its own column" ))# Display the table using kableExtravariable_table_vehicle %>%kbl() %>%kable_styling(position ="center", bootstrap_options =c("striped", "bordered", "hover"))
Variable
Description
Canton
The region in Switzerland.
Vehicle Group / Type
Type or group of the vehicle.
Fuel
Type of fuel used by the vehicle.
Month
The month of the data.
2009-2022
Number of vehicles for each respective year. Each with its own column
This data set explains the evolution of the price of brent oil over time. From this data set, we will be able to obtain precious information to compute our linear regressions concerning oil price and EVs adoptions.
Code
# Create a tibble with variable descriptionsvariable_table <-tibble(Variable =c("Date", "Price"),Description =c("The date when the price was recorded. In a day-month-year format.","The price of Brent Oil on the given date." ))# Display the table using kableExtravariable_table %>%kbl() %>%kable_styling(position ="center", bootstrap_options =c("striped", "bordered", "hover", "condensed"))
Variable
Description
Date
The date when the price was recorded. In a day-month-year format.
While this dataset contains a substantial amount of information, only a fraction of it will be pertinent to our research. It explains the evolution of the Swiss population over time through variables given below.
Code
# Create a tibble with variable descriptionsvariable_table <-tibble(Variable =c("Year", "Citizenship (category)", "Sex", "Age", "Population on 1 January", "Live birth", "Death", "Natural change", "Immigration incl. change of population type", "Emigration", "Net migration incl. change of population type", "Change of population type", "Acquisition of Swiss citizenship", "Gender change in the civil register (entry)", "Gender change in the civil register (exit)", "Statistical adjustment", "Population on 31 December", "Population change" ),Description =c("The year of the demographic data.","The categorization of the citizenship status.","Gender category.","Age category.","Population count at the beginning of the year.","Number of births in the year.","Number of deaths in the year.","Change in the population due to births and deaths.","Number of immigrants, including change of population type.","Number of emigrations.","Net migration count, including change of population type.","Change in the categorization of the population.","Number of individuals who acquired Swiss citizenship.","Number of gender changes registered (entry).","Number of gender changes registered (exit).","Adjustments made to the data for accuracy.","Population count at the end of the year.","Change in population over the year." ))# Display the table using kableExtravariable_table %>%kbl() %>%kable_styling(position ="center", bootstrap_options =c("striped", "bordered", "hover", "condensed"))
Variable
Description
Year
The year of the demographic data.
Citizenship (category)
The categorization of the citizenship status.
Sex
Gender category.
Age
Age category.
Population on 1 January
Population count at the beginning of the year.
Live birth
Number of births in the year.
Death
Number of deaths in the year.
Natural change
Change in the population due to births and deaths.
Immigration incl. change of population type
Number of immigrants, including change of population type.
Emigration
Number of emigrations.
Net migration incl. change of population type
Net migration count, including change of population type.
Change of population type
Change in the categorization of the population.
Acquisition of Swiss citizenship
Number of individuals who acquired Swiss citizenship.
This Data set shows the evolution of Google trends on 8 different terms. We chose these terms in all 3 different main Swiss national languages (French, Italian and German) to make sure we get the most accurate data possible. Those variables will help us highlight potential tendencies/trends.
Code
# Create a tibble with variable descriptions for Google Trends datavariable_table_google_trend <-tibble(Variable =c("Month", "Search Term: Voiture électrique", "Search Term: Véhicule électrique", "Search Term: EV", "Search Term: Electric Car", "Search Term: Elektromobil", "Search Term: Elektrofahrzeug", "Search Term: Elektro Auto", "Search Term: Auto Elettrica"),Description =c("The month of the data","Google Trends data for 'Voiture électrique: (Suisse)'","Google Trends data for 'Véhicule électrique: (Suisse)'","Google Trends data for 'EV: (Suisse)'","Google Trends data for 'Electric car: (Suisse)'","Google Trends data for 'Elektromobil: (Suisse)'","Google Trends data for 'Elektrofahrzeug: (Suisse)'","Google Trends data for 'Elektro Auto: (Suisse)'","Google Trends data for 'Auto Elettrica: (Suisse)'" ))# Display the table using kableExtravariable_table_google_trend %>%kbl() %>%kable_styling(position ="center", bootstrap_options =c("striped", "bordered", "hover", "condensed"))
Variable
Description
Month
The month of the data
Search Term: Voiture électrique
Google Trends data for 'Voiture électrique: (Suisse)'
Search Term: Véhicule électrique
Google Trends data for 'Véhicule électrique: (Suisse)'
Search Term: EV
Google Trends data for 'EV: (Suisse)'
Search Term: Electric Car
Google Trends data for 'Electric car: (Suisse)'
Search Term: Elektromobil
Google Trends data for 'Elektromobil: (Suisse)'
Search Term: Elektrofahrzeug
Google Trends data for 'Elektrofahrzeug: (Suisse)'
We decided to add this data set to help us compare with another country. Indeed, France is an adjacent country which might imply potential similarities in the outcome. This data set is made of variables such as the Date of the French vehicle registration or whether it is from a professional user or not. The information we are interested in concern the number of registered vehicles in the country by propulsion method over time.
Code
# Create a tibble with variable descriptions for vehicle categorization datavariable_table <-tibble(Variable =c("Date", "Ensemble des voitures particulieres", "Professionnel", "Particulier", "Crit'Air"),Description =c("The date, in year format, in which the observations are registered","The sum of vehicle in every groups","Category 'Professional' of vehicle","Category 'Passenger Car' of vehicle","Categorizes vehicles by emissions with from best to worst classes" ))# Display the table using kableExtravariable_table %>%kbl() %>%kable_styling(position ="center", bootstrap_options =c("striped", "bordered", "hover", "condensed"))
Variable
Description
Date
The date, in year format, in which the observations are registered
Ensemble des voitures particulieres
The sum of vehicle in every groups
Professionnel
Category 'Professional' of vehicle
Particulier
Category 'Passenger Car' of vehicle
Crit'Air
Categorizes vehicles by emissions with from best to worst classes
This data set is meant to determine the number of charging stations per canton, per charging power, per month, per plug type in Switzerland since November 2020. It is important to mention that a station can have multiple charging points. These values will help us to obtain more information about the Swiss adaption to EVs and their potential effects on EVs adoption by the Swiss population
Code
# Create a tibble with variable descriptions in English for charging station datavariable_table_charging <-tibble(Variable =c("year","month","stations_CH_count","stations_XY_count","locations_CH_count","locations_XY_count","plugs_CH_count","plugs_XY_count","chargingPower_CH_sum","chargingPower_XY_sum","chargingPower_CH_count","chargingPower_XY_count","chargingPower_10kW_count","chargingPower_21kW_count","chargingPower_42kW_count"),Description =c("Year of the key figures collection.","Month of the key figures collection. These are collected daily and published monthly.","Number of available charging stations in Switzerland. A station can have multiple charging points.","Number of charging stations per canton. A station can have multiple charging points. This attribute is available for all cantons, XY representing the official canton abbreviation.","Number of stations in Switzerland. A station can have multiple charging points.","Number of stations per canton. A station can have multiple charging points. This attribute is available for all cantons, XY representing the official canton abbreviation.","Number of charging plugs in Switzerland.","Number of charging plugs per plug type in Switzerland. This attribute is available for all plug types, XY corresponding to the plug type according to the Open Intercharge Protocol (OICP) version 2.2 (see below).","Total maximum charging power in kilowatts of recharge stations in Switzerland. Only charging points with known power are considered (see chargingPower_CH_count).","Total maximum charging power in kilowatts of recharge stations in a canton. Only charging points with known power are considered (see chargingPower_XY_count).","Number of recharge stations in Switzerland with known maximum charging power and for which the total maximum charging power has been taken into account (chargingPower_CH_sum).","Number of recharge stations per canton with known maximum charging power and for which the total maximum charging power has been taken into account (chargingPower_XY_sum).","Number of recharge stations in Switzerland with known maximum charging power delivering a maximum charging power of 10 kW.","Number of recharge stations in Switzerland with known maximum charging power ranging from over 10 kW to 21 kW.","Number of recharge stations in Switzerland with known maximum charging power ranging from over 21 kW to 42 kW." ))# Display the table using kableExtravariable_table_charging %>%kbl() %>%kable_styling(position ="center", bootstrap_options =c("striped", "bordered", "hover", "condensed"))
Variable
Description
year
Year of the key figures collection.
month
Month of the key figures collection. These are collected daily and published monthly.
stations_CH_count
Number of available charging stations in Switzerland. A station can have multiple charging points.
stations_XY_count
Number of charging stations per canton. A station can have multiple charging points. This attribute is available for all cantons, XY representing the official canton abbreviation.
locations_CH_count
Number of stations in Switzerland. A station can have multiple charging points.
locations_XY_count
Number of stations per canton. A station can have multiple charging points. This attribute is available for all cantons, XY representing the official canton abbreviation.
plugs_CH_count
Number of charging plugs in Switzerland.
plugs_XY_count
Number of charging plugs per plug type in Switzerland. This attribute is available for all plug types, XY corresponding to the plug type according to the Open Intercharge Protocol (OICP) version 2.2 (see below).
chargingPower_CH_sum
Total maximum charging power in kilowatts of recharge stations in Switzerland. Only charging points with known power are considered (see chargingPower_CH_count).
chargingPower_XY_sum
Total maximum charging power in kilowatts of recharge stations in a canton. Only charging points with known power are considered (see chargingPower_XY_count).
chargingPower_CH_count
Number of recharge stations in Switzerland with known maximum charging power and for which the total maximum charging power has been taken into account (chargingPower_CH_sum).
chargingPower_XY_count
Number of recharge stations per canton with known maximum charging power and for which the total maximum charging power has been taken into account (chargingPower_XY_sum).
chargingPower_10kW_count
Number of recharge stations in Switzerland with known maximum charging power delivering a maximum charging power of 10 kW.
chargingPower_21kW_count
Number of recharge stations in Switzerland with known maximum charging power ranging from over 10 kW to 21 kW.
chargingPower_42kW_count
Number of recharge stations in Switzerland with known maximum charging power ranging from over 21 kW to 42 kW.
# Create a tibble with variable descriptions for the Swiss population datasetvariable_table_swiss_pop <-tibble(Variable =c("Canton", "Total Population", "Age Groups", "Sex", "Citizenship", "Marital Status", "Typology: Area with urban character"),Description =c("The name of the canton in Switzerland.","Total number of permanent residents in the canton.","Population broken down into age groups: 0–19, 20–64, 65 and over.","Population broken down by sex: Male and Female.","Population broken down by citizenship: Swiss and Foreigner.","Population broken down by marital status: Single, Married, Widowed, Divorced, Unmarried, In a registered partnership, Partnership dissolved.","Typology of the area based on urban character: Urban core, Area influenced by urban cores, Area beyond urban influence." ))# Display the table using kableExtravariable_table_swiss_pop %>%kbl() %>%kable_styling(position ="center", bootstrap_options =c("striped", "bordered", "hover"))
Variable
Description
Canton
The name of the canton in Switzerland.
Total Population
Total number of permanent residents in the canton.
Age Groups
Population broken down into age groups: 0–19, 20–64, 65 and over.
Sex
Population broken down by sex: Male and Female.
Citizenship
Population broken down by citizenship: Swiss and Foreigner.
Marital Status
Population broken down by marital status: Single, Married, Widowed, Divorced, Unmarried, In a registered partnership, Partnership dissolved.
Typology: Area with urban character
Typology of the area based on urban character: Urban core, Area influenced by urban cores, Area beyond urban influence.
Initially, while attempting to format the dataset, we discovered the generation of numerous NAs. Upon delving deeper into the data, we identified two distinct date formats: the first being [DD-MMM-YYYY] and the second [MMM DD, YYYY]. Consequently, the initial date formatting was ineffective. Therefore, we undertook the task of matching the two tables with the same date format.
Another issue we encountered was to present the date in a standardized form across all our dataset to perform time series analyses. For that, we had to change the abbreviated months names (i.e. Jan, Feb, etc.) into numbers.
Code
# Format 1: DD-MMM-YYYY (e.g., 15-Apr-2020)oil_df_1 <- oil_prices_data[1:8360,] %>%separate(Date, into =c("Day", "Month", "Year"), sep ="-") %>%mutate(Date =dmy(paste(Day, Month, Year)))# Format 2: MMM DD, YYYY (e.g., Apr 22, 2020)# Handling the separator with space and commaoil_df_2 <- oil_prices_data[8361:nrow(oil_prices_data),] %>%separate(Date, into =c("Month", "Day", "Year"), sep =" ", extra ="merge") %>%mutate(Day =word(Day, 1), # Extracts just the day partDate =mdy(paste(Month, Day, Year)))# Merge and filter for dates after 2005df_oil <-rbind(oil_df_1, oil_df_2) %>%filter(year(Date) >=2005) %>%select(Date, Price)# Display cleaned datareactable( df_oil, # Use your oil prices dataframecolumns =list(Date =colDef(align ="center", # Center align the date columnminWidth =150 ),Price =colDef(align ="right", # Right align the price columnstyle =function(value) {# Apply conditional formatting based on the price valueif (value >120) { color <-"green"# Green for high prices } elseif (value <30) { color <-"red"# Red for low prices } else { color <-"black"# Default color for other values }list(color = color) } ) ),highlight =TRUE, # Highlight rows on hoverdefaultPageSize =10, # Display 10 rows per pagepaginationType ="numbers", # Use numbers for page navigationsearchable =TRUE, # Make the table searchablesortable =TRUE, # Allow sortingresizable =TRUE# Allow column resizing)
2.2.2 Data Wrangling : Google trend clean
Comprehending Google Trends information involves understanding the contextualization of the provided figures. The given data is standardized which limits the range of information we can obtain from it.
The crucial element for effective narration lies in utilizing the normalized Trends data. This normalization indicates that when observing search interest trends over time, it is interpreted as a ratio relative to all searches conducted on all topics on Google during that specific period and location. Likewise, when assessing regional search interest for a specific topic, it is construed as the search interest for that particular topic in a given region relative to all searches on all topics on Google in that same place and time.
To clean and process eight Google Trends datasets related to different search terms, we created a function process_dataset() that reads each CSV file, removes date indices, excludes the first row, checks for missing values, renames columns, converts types, and standardizes the date format. Then, we iterated through each dataset, merged them based on the “Date” column, summed values for each search term per date, and normalized these values between 1 and 100.
Code
dataset_names <-c("googletrends_auto-elettrica_2005-2022.csv","googletrends_elektro-auto_2005-2022.csv","googletrends_elektrofahrzeug_2005-2022.csv","googletrends_elektromobil_2005-2022.csv","googletrends_eletric-car_2005-2022.csv","googletrends_EV_2005-2022.csv","googletrends_vehicule-electrique_2005-2022.csv","googletrends_voiture-electrique_2005-2022.csv")# Function to process each datasetprocess_dataset <-function(file_path) {# Read the dataset google_trends_data <-read.csv(file_path)# Remove the dates from the index google_trends_data <- google_trends_data |>rownames_to_column(var ="Date")# Remove the first row using slice google_trends_data <-slice(google_trends_data, -1)# Check for NAcat("NA count for", file_path, ": ", sum(is.na(google_trends_data$Date)), "\n")cat("NA count for SearchCount in", file_path, ": ", sum(is.na(google_trends_data$Catégorie...Toutes.catégories)), "\n")# Rename colcolnames(google_trends_data)[2] <-"SearchCount"# Convert to numeric google_trends_data$SearchCount <-as.numeric(google_trends_data$SearchCount)# Convert the column to date with the desired format google_trends_data$Date <-as.Date(paste(google_trends_data$Date, "01", sep ="-"))return(google_trends_data)}# Process each dataset and store in a listprocessed_datasets <-list()for (dataset_name in dataset_names) { file_path_gt <-file.path("../data", dataset_name) processed_dataset <-process_dataset(file_path_gt) processed_datasets[[dataset_name]] <- processed_dataset}#> NA count for ../data/googletrends_auto-elettrica_2005-2022.csv : 0 #> NA count for SearchCount in ../data/googletrends_auto-elettrica_2005-2022.csv : 0 #> NA count for ../data/googletrends_elektro-auto_2005-2022.csv : 0 #> NA count for SearchCount in ../data/googletrends_elektro-auto_2005-2022.csv : 0 #> NA count for ../data/googletrends_elektrofahrzeug_2005-2022.csv : 0 #> NA count for SearchCount in ../data/googletrends_elektrofahrzeug_2005-2022.csv : 0 #> NA count for ../data/googletrends_elektromobil_2005-2022.csv : 0 #> NA count for SearchCount in ../data/googletrends_elektromobil_2005-2022.csv : 0 #> NA count for ../data/googletrends_eletric-car_2005-2022.csv : 0 #> NA count for SearchCount in ../data/googletrends_eletric-car_2005-2022.csv : 0 #> NA count for ../data/googletrends_EV_2005-2022.csv : 0 #> NA count for SearchCount in ../data/googletrends_EV_2005-2022.csv : 0 #> NA count for ../data/googletrends_vehicule-electrique_2005-2022.csv : 0 #> NA count for SearchCount in ../data/googletrends_vehicule-electrique_2005-2022.csv : 0 #> NA count for ../data/googletrends_voiture-electrique_2005-2022.csv : 0 #> NA count for SearchCount in ../data/googletrends_voiture-electrique_2005-2022.csv : 0# Merge datasets based on the "Date" columnmerged_data <-reduce(processed_datasets, left_join, by ="Date")# Sum the values for each search term for a given datedf_gtrends <- merged_data %>%rowwise() %>%mutate(Sum_SearchCount =sum(c_across(starts_with("SearchCount"))))# Normalize the Sum_SearchCount values between 1 and 100df_gtrends$SearchRatio <- df_gtrends$Sum_SearchCount /8# Print the resultdf_gtrends <- df_gtrends[,-(2:10)]#display cleaned datareactable( df_gtrends,columns =list(Date =colDef(align ="center", # Center align the date columnminWidth =150 ),SearchRatio =colDef(align ="right", # Right align the SearchRatio columnstyle =function(value) {if (value >45) { color <-"green"# Green for values greater than 50 } elseif (value <5) { color <-"red"# Red for values less than 5 } else { color <-"black"# Default color for other values }list(color = color) } ) ),highlight =TRUE, # Highlight rows on hoverdefaultPageSize =10, # Display 10 rows per pagepaginationType ="numbers", # Use numbers for page navigationsearchable =TRUE, # Make the table searchablesortable =TRUE, # Allow sortingresizable =TRUE# Allow column resizing)
2.2.3 Cleaning of demographic_data
The main issue with this data set was to transform it in a way that makes it useful for our analysis. We first had to remove all rows containing category summaries in the middle of the data.
We then formulated to following hypothesizes:
Male and Female present the same attitude towards electric vehicles
Swiss and Foreign citizen living in Switzerland present the same attitude towards electric vehicles
People who are not allowed to drive do not have any impact on electric vehicles use
We then decided to do the following cleaning:
Only kept the “Total” for the Male-Female category
Only kept the “Total” for the Swiss-Foreign category
Only kept people aged between 18 and 99. (People aged over 99 account for 0.02% of the population)
Then, instead of keeping a raw data set with all ages between 18 and 99, we decided to group them in widely accepted age segments, namely Generation Z, Millennials, Generation X and Baby boomers. This categorization will help us to analyse whether different generations have a different approach to their mobility or not.
Code
# Clean and process the demographic datadf_demographic <- demographic_data %>%filter(Year >=2005, Year <=2022) %>%filter(str_detect(Sex, "total"), str_detect(`Citizenship (category)`, "total")) %>%mutate(Age_clean =gsub(" years", "", Age)) %>%filter(!str_detect(Age_clean, "total")) %>%mutate(Age_num =as.numeric(Age_clean)) %>%filter(!is.na(Age_num), Age_num >=18, Age_num <=98) %>%select(Year, Age = Age_num, `Population on 1 January`) %>%mutate(Generation =cut(Age, breaks =c(17, 26, 42, 58, Inf), labels =c("Generation Z", "Millennials", "Generation X", "Baby Boomers"), include.lowest =TRUE) ) %>%group_by(Year, Generation) %>%summarise(Population =sum(`Population on 1 January`, na.rm =TRUE)) %>%pivot_wider(names_from = Generation, values_from = Population)#> Warning: There was 1 warning in `mutate()`.#> i In argument: `Age_num = as.numeric(Age_clean)`.#> Caused by warning:#> ! NAs introduced by coercionreactable( df_demographic, columns =list(Year =colDef(align ="center", # Center align the year columnminWidth =100 ),`Generation Z`=colDef(align ="right", # Right align the population columnstyle =function(value) { color <-ifelse(value >860000, "green", "black") # Green for population over 1 millionlist(color = color) } ),Millennials =colDef(align ="right",style =function(value) { color <-ifelse(value >1900000, "green", "black")list(color = color) } ),`Generation X`=colDef(align ="right",style =function(value) { color <-ifelse(value >2000000, "green", "black")list(color = color) } ),`Baby Boomers`=colDef(align ="right",style =function(value) { color <-ifelse(value >2300000, "green", "black")list(color = color) } ) ),highlight =TRUE, # Highlight rows on hoverdefaultPageSize =10, # Display 10 rows per pagepaginationType ="numbers", # Use numbers for page navigationsearchable =TRUE, # Make the table searchablesortable =TRUE, # Allow sortingresizable =TRUE# Allow column resizing)
2.2.4 Data Wrangling : Swiss vehicle clean
Code
# Define a function to process vehicle data, excluding the first row as it's not actual dataprocess_vehicle_data <-function(vehicle_data, start_year, end_year) {# the first row is a header or metadata and should be excluded vehicle_data <- vehicle_data[-1, ] col_names <-c("Canton", "VehicleGroupType", "Fuel", "Month", paste0("X", start_year:end_year))names(vehicle_data) <- col_names vehicle_data %>%filter(!str_detect(trimws(VehicleGroupType), "^>")) %>%rename(Location = Canton, VehicleType = VehicleGroupType) %>%mutate(VehicleType =str_remove(VehicleType, "^\\.\\.\\.\\s*")) %>%pivot_longer(cols =all_of(paste0("X", start_year:end_year)), names_to ="Year", values_to ="Count") %>%mutate(Year =as.numeric(str_remove(Year, "X")),MonthNum =match(Month, month.name),Date =as.Date(paste(Year, ifelse(is.na(MonthNum), 1, MonthNum), "01", sep ="-"), format ="%Y-%m-%d")) %>%select(-Month, -Year, -MonthNum)}# Process 2005 to 2008 and 2009 to 2022 datav_2005_2008 <-process_vehicle_data(vehicle_data_2005_2008, 2005, 2008)v_2009_2022 <-process_vehicle_data(vehicle_data_2009_2022, 2009, 2022)# Merge and arrange datadf_v <-bind_rows(v_2005_2008, v_2009_2022) %>%arrange(Date)# Canton and Fuel Type Standardizationstandard_names <-c("Switzerland"="Switzerland", "Zürich"="ZH", "Bern"="BE", "Luzern"="LU","Uri"="UR", "Schwyz"="SZ", "Obwalden"="OW", "Nidwalden"="NW","Glarus"="GL", "Zug"="ZG", "Fribourg"="FR", "Solothurn"="SO","Basel-Stadt"="BS", "Basel-Landschaft"="BL", "Schaffhausen"="SH","Appenzell Ausserrhoden"="AR", "Appenzell Innerrhoden"="AI", "St. Gallen"="SG", "Graubünden"="GR", "Aargau"="AG", "Thurgau"="TG", "Ticino"="TI", "Vaud"="VD", "Valais"="VS","Neuchâtel"="NE", "Genève"="GE", "Jura"="JU", "Confederation"="Confederation")df_v <- df_v %>%mutate(Location =iconv(Location, from ="latin1", to ="UTF-8")) %>%mutate(Location =map_chr(str_split(Location, " / "), ~ .x[1])) %>%mutate(Location = standard_names[Location],Fuel =case_when( Fuel %in%c("Petrol-electricity: conventional hybrid", "Diesel-electricity: conventional hybrid") ~"Conventional hybrid", Fuel %in%c("Petrol-electricity: plug-in hybrid", "Diesel-electricity: plug-in hybrid") ~"Plug-in hybrid", Fuel =="Gas (monovalent and bivalent)"~"Gas",TRUE~ Fuel))# Count number of vehicles for a particular year#vehicle_count_2022 <- df_v %>%# filter(Location == "Switzerland", year(Date) == 2023, VehicleType == "Passenger car") %>%# summarize(TotalCount = sum(Count))
Redundancy
The dataset, representing new vehicle registrations in Switzerland from 2005 onwards, exhibited redundancy in its structure. For example, the data contained both main categories (like ‘> Passenger cars’) and their respective sub-categories (‘… Passenger car’ and ‘.. Heavy passenger car’). On examination, it was observed that the counts under the main categories were simply aggregates of the counts of their sub-categories. Such redundancy could lead to double counting in analytical processes.
We addressed this issue by removing main categories that were aggregates of their sub-categories, preventing potential double counting in analyses. For two subsets of data (2005 to 2008 and 2009 to 2022), We filtered out main categories, cleaned and standardized the column names, reshaped the data set from wide to long format to facilitate analysis, and extracted and formatted the year information for each observation. This process allowed for a more granular and consistent data set for further analysis and interpretation.
Merging and Joining
As the vehicle data was split across multiple files, it was necessary to combine them for a holistic view.
We used bind_rowsto create df_v, then sorted the dataset by year to ensure a structured chronological view of the data.
Refinement and Vehicle Classification Insights
Some canton names in the dataset had special characters not properly encoded, displaying as hexadecimal escape sequences. To correct this, we used iconv to properly encode these characters from “latin1” to “UTF-8”. Additionally, where multiple names were provided for cantons (separated by slashes), we retained only the first name. We standardized the canton names using a predefined list (standard_names).
We unified the date representation by combining ‘Year’ and ‘Month’ information, matching month names to their corresponding numeric values, then merged this information with the year, and formatted it as “YYYY-MM-DD” to generate a standard date format. This transformation streamlines time series analyses and provides a more intuitive representation of the data’s temporal dimension.
We simplified the classification of hybrid vehicles by merging different categories of conventional and plug-in hybrids into two main groups: “Conventional hybrid” and “Plug-in hybrid”, respectively. This simplification aimed to streamline analysis by grouping similar types together.
The “Gas” fuel type was renamed from “Gas (monovalent and bivalent)” for clarity and consistency in the dataset.
Further context was provided on different hybrid types:
Conventional Hybrids: These vehicles, powered by petrol or diesel without plug-in capability, might exhibit different adoption trends due to their longer existence in the market.Indeed, they have been around for longer and may have a different adoption trend compared to newer technologies.
Plug-in Hybrids: With larger batteries and the ability to charge from an electric outlet, these vehicles enable all-electric operation for limited distances. The presence of charging infrastructure might impact their adoption differently, distinguishing them from conventional hybrids. Adoption might be reflected differently due to the need for charging infrastructure.
Rows with 0
Retaining rows with a Count of 0 ensures the completeness of our dataset, indicating periods when specific vehicle types or fuel categories had no registrations. This not only provides a holistic view of vehicle adoption trends over time but also aids in generating continuous time series visualizations without gaps, offering a true representation of the data.
This dataset will be used to compare our data in Switzerland with a bordering country (FR)
It is important to note that this data set contains all registered vehicles in a given year (vs. all new registered cars for our Swiss data) We will only keep the vehicles used for personal use (not the ones for professional use), to match our Swiss dataset
We decided to remove some anecdotal observations (i.e Hydrogen, Unknown, etc.) as their production / use is marginal. Moreover, we have decided to regroup the different kind of hybrid motors into two Hybrid categories. The 2 categories are the plugable hybrid vehicle HR (petrol or diesel) and the non-plugable hybrid vehicles HNR (petrol or diesel). This was done to match our Swiss data set.
The main issue with this data set was to set it in a way where it is comparable to our Swiss cars data set. Indeed, this dataset presents the total of all cars in France for a given year and type, while our Swiss data set accounts for new registration of cars for a given year and type.
To be able to compare two data sets, we decided to format the French data set in the following way:
Remove categories that are not relevant for our analysis, and widely under-represented in the population (i.e Gaz, hydrogen)
Focus on the private use of cars (vs. professional), because the decision to use a certain type of cars for professional reasons are often explained by factors hard to capture in our analysis (i.e bundle deals, greenwashing). We therefore hypothesized that private use of a certain type of car better gives insights on population view.
The match our swiss data set (new registration per year), we computed the difference of total cars registered in France per years. Having only the data between 2011 and 2022, we have “lost” the insights for 2011. Indeed, when creating the deltas (difference) columns, 2011 deltas could not be computed (no data for 2010), we therefore decided to delete that year from our data
Code
# Only taking the private cars from this data and transforming the datadf_v_fr <- france_v[25:37, ] %>%t() %>%as_tibble() %>%setNames(.[1, ]) %>%slice(-1) %>%mutate(Year =2011:2022) %>%select(-c("Particulier", "Gaz", "Gaz HNR", "Gaz HR", "Hydrogène et autre ZE", "Inconnu")) %>%mutate(across(-Year, ~floor(as.numeric(.)))) %>%mutate(Conventional_Hybrid =as.numeric(`Diesel HNR`) +as.numeric(`Essence HNR`),Plug_in_Hybrid =as.numeric(`Diesel HR`) +as.numeric(`Essence HR`),across(c(Diesel, Essence, Conventional_Hybrid, Plug_in_Hybrid, Electrique), as.numeric),Diesel_delta = Diesel -lag(Diesel),Essence_delta = Essence -lag(Essence),Conventional_Hybrid_delta = Conventional_Hybrid -lag(Conventional_Hybrid),Plug_in_Hybrid_delta = Plug_in_Hybrid -lag(Plug_in_Hybrid),Electrique_delta = Electrique -lag(Electrique) ) %>%filter(!is.na(Diesel_delta)) %>%select(Date = Year, Diesel, Diesel_delta, Essence, Essence_delta, Conventional_Hybrid, Conventional_Hybrid_delta, Plug_in_Hybrid, Plug_in_Hybrid_delta, Electrique, Electrique_delta) %>%mutate(Date =as.Date(paste(Date, "-01-01", sep =""), format ="%Y-%m-%d"))#> Warning: The `x` argument of `as_tibble.matrix()` must have unique column#> names if `.name_repair` is omitted as of tibble 2.0.0.#> i Using compatibility `.name_repair`.# Display cleaned datareactable(head(df_v_fr, 100), sortable =TRUE, searchable =TRUE)
2.2.6 Availability of charging stations
This data set will be used to explore and analyze the effects of charging station availability on EVs adoption.
However, two important points are to note.
We were unable to find data before November 2020
Charging station availability and EV in market are likely strongly reciprocally correlated.
Moreover, it is important to keep standardized dates and locations
We merges ‘year’ and ‘month’ columns to create a ‘Date’ column in the format “YYYY-MM-01”, subsequently reorganizing the dataframe to position ‘Date’ as the first column and removing the original ‘year’ and ‘month’ columns.
Code
# Combine 'year' and 'month' columns to create a new 'Date' columncharging_station$Date <-as.Date(paste(charging_station$year, charging_station$month, "01", sep ="-"), format ="%Y-%m-%d")# Rearrange columns with 'Date' as the first column and drop 'year' and 'month'df_charging_station <- charging_station %>%select(Date, everything()) %>%select(-year, -month)# Display cleaned datareactable(df_charging_station,sortable =TRUE, searchable =TRUE)
2.2.7 Swiss Population
We chose to use the population data from the year 2022 to ensure the most current and relevant demographic context, providing a contemporary snapshot that aligns closely with the latest trends in electric vehicle registrations.
Assuming the relevant data starts from row 5, canton names are in the first column, and the population figures for 2022 are in the second column.
Code
df_swisspop <- df_swisspop %>%slice(-1:-4) %>%# Remove the first 4 rowsselect(Canton =1, TotalPopulation =2) # Select only the canton names and population figures# Remove rows with NAs in the Canton columndf_swisspop <- df_swisspop %>%filter(!is.na(Canton))# Map Canton names to abbreviationsdf_swisspop <- df_swisspop %>%mutate(CantonAbbreviation =case_when( Canton =="Zurich"~"ZH", Canton =="Bern"~"BE", Canton =="Lucerne"~"LU", Canton =="Uri"~"UR", Canton =="Schwyz"~"SZ", Canton =="Obwalden"~"OW", Canton =="Nidwalden"~"NW", Canton =="Glarus"~"GL", Canton =="Zug"~"ZG", Canton =="Fribourg"~"FR", Canton =="Solothurn"~"SO", Canton =="Basel-Stadt"~"BS", Canton =="Basel-Landschaft"~"BL", Canton =="Schaffhausen"~"SH", Canton =="Appenzell A. Rh."~"AR", Canton =="Appenzell I. Rh."~"AI", Canton =="St. Gallen"~"SG", Canton =="Graubünden"~"GR", Canton =="Aargau"~"AG", Canton =="Thurgau"~"TG", Canton =="Ticino"~"TI", Canton =="Vaud"~"VD", Canton =="Valais"~"VS", Canton =="Neuchâtel"~"NE", Canton =="Geneva"~"GE", Canton =="Jura"~"JU",TRUE~NA_character_# For unrecognized cantons ))# Map Canton names to KANTONSNUMdf_swisspop <- df_swisspop %>%mutate(KANTONSNUM =case_when( Canton =="Graubünden"~18, Canton =="Bern"~2, Canton =="Valais"~23, Canton =="Vaud"~22, Canton =="Ticino"~21, Canton =="St. Gallen"~17, Canton =="Zurich"~1, Canton =="Fribourg"~10, Canton =="Lucerne"~3, Canton =="Aargau"~19, Canton =="Uri"~4, Canton =="Thurgau"~20, Canton =="Schwyz"~5, Canton =="Jura"~26, Canton =="Neuchâtel"~24, Canton =="Solothurn"~11, Canton =="Glarus"~8, Canton =="Basel-Landschaft"~13, Canton =="Obwalden"~6, Canton =="Nidwalden"~7, Canton =="Geneva"~25, Canton =="Schaffhausen"~14, Canton =="Appenzell A. Rh."~15, Canton =="Zug"~9, Canton =="Appenzell I. Rh."~16, Canton =="Basel-Stadt"~12,TRUE~NA_integer_# For unrecognized cantons ))df_swisspop$TotalPopulation <-as.integer(df_swisspop$TotalPopulation)# Filter out rows where CantonAbbreviation is NAdf_swisspop <- df_swisspop %>%filter(!is.na(CantonAbbreviation))# Display cleaned datareactable(df_swisspop,sortable =TRUE, searchable =TRUE)
3 Exploratory data analysis
3.1 Switzerland
3.1.1 seasonality
Code
#creating dataset for the three seasonality graphspassenger_cars_processed <- df_v %>%filter(VehicleType =="Passenger car") %>%mutate(YearMonth =floor_date(Date, "month")) %>%group_by(YearMonth) %>%summarise(Count =sum(Count, na.rm =TRUE)) %>%ungroup() %>%mutate(Year =year(YearMonth), Month =factor(month(YearMonth), levels =1:12, labels = month.abb)) %>%arrange(Year, Month)# plot1p_seaso_1 <-ggplot(passenger_cars_processed, aes(x = YearMonth, y = Count)) +geom_line(color ="darkblue", size =0.5) +labs(title ="Passenger Car Adoption Over Time in Switzerland",x ="Date",y ="Number of Passenger Cars Registered") +theme_minimal() +scale_x_date(date_breaks ="1 year", date_labels ="%Y") +geom_smooth(method ="loess", se =FALSE, color ="blue") +theme(axis.text.x =element_text(angle =45, hjust =1))#> Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.#> i Please use `linewidth` instead.# Convert to an interactive plotly objectinteractive_plot_seaso_1 <-ggplotly(p_seaso_1, width =600, height =400)# Display the interactive plotinteractive_plot_seaso_1
The blue line represents a smoothed trend, indicating an initial increase in car registrations until around 2014-2015, followed by a gradual decline. The black line shows the actual number of cars registered, with significant variability. We will call this variation seasonality which is better represented in the following graph.
Code
# Plotting the data with ggplot2, showing the trend within each yearp_seaso_2 <-ggplot(passenger_cars_processed, aes(x = Month, y = Count, group = Year, color =as.factor(Year))) +geom_smooth(se =FALSE, method ="loess", span =0.5, size =0.7) +labs(title ="Monthly Passenger Car Registrations by Year",x ="Month",y ="Number of Passenger Cars Registered",color ="Year") +theme_minimal() +scale_color_viridis_d() +theme(legend.position ="bottom", axis.text.x =element_text(angle =45, hjust =1))# Convert to an interactive plotly objectinteractive_plot_seaso_2 <-ggplotly(p_seaso_2, width =600, height =400)# Adjust plotly settings if needed, such as margins or layoutinteractive_plot_seaso_2 <- interactive_plot_seaso_2 %>%layout(margin =list(l =40, r =10, b =40, t =40), # Adjust marginslegend =list(orientation ="h", x =0, xanchor ="left", y =-0.2)) # Adjust legend position# Display the interactive plotinteractive_plot_seaso_2
This pattern suggests a seasonal trend with a mid-year peak and a year-end increase. 2020 reacts differently than other years. We suggest that it is probably related to Covid policies.
Code
# Plotting the data with ggplot2, showing the trend within each yearp_seaso_3 <-ggplot(passenger_cars_processed, aes(x = Month, y = Count, group = Year, color =as.factor(Year))) +geom_line() +facet_wrap(~ Year, scales ="free_y") +# Facet by year with free y scaleslabs(title ="Seasonal Trends in Passenger Car Registrations",x ="Month",y ="Number of Passenger Cars Registered") +theme_minimal() +scale_color_viridis_d(guide =FALSE) +# Use viridis color scale and remove the guide/legendtheme(axis.text.x =element_text(angle =45, hjust =1)) +# Rotate x-axis labels by 45 degreestheme(axis.text.x =element_blank(), # This will remove the month labelsaxis.text.y =element_blank(), # This will remove the month labelsaxis.ticks.x =element_blank(), # This will remove the ticks on the x-axislegend.position ="none") # Remove the legend to clean up the plot# Convert to an interactive plotly objectinteractive_plot_seaso_3 <-ggplotly(p_seaso_3, width =600, height =400) %>%layout(xaxis =list(tickmode ="array",tickvals =1:12,ticktext = month.abb))# Display the interactive plotinteractive_plot_seaso_3
This version of the graphs helps us visualizing the evolution of registration for each year individually. As mentioned above, 2020 is the only year which show a decreasing peak instead of an increasing one as it is presented for all other years.
3.1.2 Vehicule Registration by Fuel time over time
Code
# Filter df_v for specific fuel types and vehicle typefiltered_df <- df_v %>%filter(Fuel %in%c("Petrol", "Diesel", "Conventional hybrid", "Plug-in hybrid", "Electricity") & VehicleType =="Passenger car")# Group by Date and Fuel type, and summarize the countfuel_type_trends <- filtered_df %>%group_by(Date, Fuel) %>%summarize(Count =sum(Count, na.rm =TRUE), .groups ='drop') # Use .groups = 'drop' to ungroup immediately# Plotting the trends over time by fuel typep_fuel_over_time <-ggplot(fuel_type_trends, aes(x = Date, y = Count, color = Fuel)) +geom_line(alpha =0.3) +# Plot the actual linesgeom_smooth(aes(group = Fuel), se =FALSE, method ="loess", span =0.1) +# Add smoothed lines per fuel typelabs(title ="Vehicle Registrations by Fuel Type Over Time",x ="Date",y ="Number of Vehicles Registered") +theme_minimal() +theme(legend.position ="bottom") # Adjust legend position to the bottom# Convert to an interactive plotly objectinteractive_plot_fuel_over_time <-ggplotly(p_fuel_over_time, width =600, height =400)# Adjust plotly settings interactive_plot_fuel_over_time <- interactive_plot_fuel_over_time %>%layout(legend =list(orientation ="h", x =0, xanchor ="left", y =-0.2))# Display the interactive plotinteractive_plot_fuel_over_time
The graph above shows the vehicle registrations in Switzerland by fuel type from 2005 to 2023.
On the one hand, it highlights the recent decrease in new registrations of thermic vehicles since 2017. On the other hand, the three EVs named as Conventional and Plug-in hybrids along with electricity ones are gradually increasing since approximately the same period. (In fact, fully electric cars and Conventional hybrids have even reached a higher level of vehicle registration in the past years, spotlighting the EV tendency in recent years.)
3.1.3 Map
3.1.4.1 Count of Electricity car Registration for all years per cantons
swissBOUNDARIES3D_1_4_TLM_KANTONSGEBIET.shp contains the boundaries of the cantons of Switzerland.
The choice to display the sum of electric vehicle registrations over all years on the map was made to provide a comprehensive historical perspective, highlighting the total adoption of electric vehicles in each Swiss canton since the beginning of the dataset’s timeframe. This approach effectively captures the cumulative impact of electric vehicle adoption across the country.
The process involved filtering vehicle registration data for electric passenger cars and summing up the total registrations for each Swiss canton. This data was then combined with population figures and geographic boundaries to calculate electric vehicle (EV) registrations per capita, providing a standardized comparison of EV adoption across cantons.
Code
# Read in the shapefile for Swiss cantonsswiss_cantons <-st_read("../data/CH_map/swissBOUNDARIES3D_1_4_TLM_KANTONSGEBIET.shp")#> Reading layer `swissBOUNDARIES3D_1_4_TLM_KANTONSGEBIET' from data source `C:\Users\UrsHu\Pillars\Learn\Academic\Master\Semestre 1\Data Science\0_group_project\dsfba_project\data\CH_map\swissBOUNDARIES3D_1_4_TLM_KANTONSGEBIET.shp' #> using driver `ESRI Shapefile'#> Simple feature collection with 50 features and 20 fields#> Geometry type: POLYGON#> Dimension: XYZ#> Bounding box: xmin: 2490000 ymin: 1080000 xmax: 2830000 ymax: 1300000#> z_range: zmin: 193 zmax: 4610#> Projected CRS: CH1903+ / LV95 + LN02 height# Define canton abbreviations for matchingabbreviation_values <-c("ZH", "BE", "LU", "UR", "SZ", "OW", "NW", "GL", "ZG", "FR", "SO", "BS", "BL", "SH", "AR", "AI", "SG", "GR", "AG", "TG", "TI", "VD", "VS", "NE", "GE", "JU")# Prepare the EV data with sum over all yearsdf_v_map <- df_v %>%filter(!Location %in%c("Switzerland", "Confederation"), Fuel =="Electricity", VehicleType =="Passenger car") %>%mutate(KANTONSNUM =match(Location, abbreviation_values)) %>%group_by(KANTONSNUM) %>%summarize(TotalEV =sum(Count), .groups ='drop')# Merge EV data with population datadf_v_map <-left_join(df_v_map, df_swisspop, by =c("KANTONSNUM"="KANTONSNUM"))str(df_v_map)#> tibble [26 x 5] (S3: tbl_df/tbl/data.frame)#> $ KANTONSNUM : num [1:26] 1 2 3 4 5 6 7 8 9 10 ...#> $ TotalEV : int [1:26] 29541 11652 5365 325 2960 551 690..#> $ Canton : chr [1:26] "Zurich" "Bern" "Lucerne" "Uri" ...#> $ TotalPopulation : int [1:26] 1579967 1051437 424851 37317 1649..#> $ CantonAbbreviation: chr [1:26] "ZH" "BE" "LU" "UR" ...# Calculate EV registrations per capitadf_v_map <- df_v_map %>%mutate(EV_per_Capita = TotalEV / TotalPopulation)# Merge with shapefile datamap_data <-left_join(swiss_cantons, df_v_map, by ="KANTONSNUM")# Ensure the geometries are valid and the CRS is set to WGS 84# Check if 'map_data' is already an sf objectif (!inherits(map_data, "sf")) { map_data_sf <-st_as_sf(map_data, wkt ="geometry")} else { map_data_sf <- map_data}# Ensure the geometries are valid and the CRS is setmap_data_sf <-st_make_valid(map_data_sf)# Reproject the data to WGS 84 (EPSG:4326)map_data_sf <-st_transform(map_data_sf, crs =4326)# Create color palettes for the 'Total' and 'EV_per_Capita' columnscolor_palette_total <-colorNumeric(palette ="viridis", domain = map_data_sf$TotalEV)color_palette_per_capita <-colorNumeric(palette ="viridis", domain = map_data_sf$EV_per_Capita)# Create the leaflet mapsleaflet_map_total <-leaflet(map_data_sf) %>%addProviderTiles(providers$CartoDB.Positron) %>%addPolygons(fillColor =~color_palette_total(TotalEV),weight =1,color ="#FFFFFF",fillOpacity =0.7,popup =~paste(NAME, "<br>Total EV Registrations: ", TotalEV) ) %>%addLegend(pal = color_palette_total, values =~TotalEV, opacity =0.7, title ="Total EV <br> Registrations",position ="topright" )leaflet_map_per_capita <-leaflet(map_data_sf) %>%addProviderTiles(providers$CartoDB.Positron) %>%addPolygons(fillColor =~color_palette_per_capita(EV_per_Capita),weight =1,color ="#FFFFFF",fillOpacity =0.7,popup =~paste(NAME, "<br>EV Registrations per Capita: ", round(EV_per_Capita, 3)) ) %>%addLegend(pal = color_palette_per_capita, values =~EV_per_Capita, opacity =0.7, title ="EV Registrations <br> per Capita",position ="topright" )# Print the maps to view themleaflet_map_total
3.1.4.2 Count of Electricity car Registration for all years per cantons Standardized
For example, Zurich (ZH) has a relatively lower EV_per_Capita value (0.01870) despite a high total number of EV registrations (29,541), due to its large population (1,579,967). In contrast, Zug (ZG) shows a higher EV_per_Capita (0.04666) with fewer EV registrations (6,120) but a much smaller population (131,164), indicating a greater adoption rate when adjusted for population size.
The limitation of this approach is that it considers the total population, not accounting for the segment of the population that is of driving age or interested in vehicle ownership, which could further refine the EV adoption rates.
Code
leaflet_map_per_capita
3.2 Google Trend
Code
ggplot(df_gtrends, aes(x = Date, y = SearchRatio)) +geom_line(color ="darkgreen", size =1, stat='smooth', se =FALSE, method ="loess", span =0.1, size =1) +labs(x ="Date", y ="Google Search", title ="Google search About EV in Switzerland")#> Warning: Duplicated aesthetics after name standardisation: size
Another interesting point to look out is the Google search about EV engine in Switzerland. As we can see, it seems to have skyrocketed since 2016. This allows us to get an overview of the Swiss population interest concerning this topic and comfort us towards our initial predictions.
3.3 Oil
The above chart represents the oil price evolution through the last two decades. We can observe a quite high degree of volatility concerning the oil valuation. Nevertheless, it seems important to highlight that this value has greatly increased since the past 3 years.
The fig.show='animate' option tells Quarto to render the plot as an animation.
Code
## basic plot#ggplot(df_oil, aes(x = Date , y = Price)) +# geom_line(color = "darkred", size = 1) +# labs(x = "Date", y = "Price", title = "Oil Price Over Time")# Create a ggplot object with your datap <-ggplot(df_oil, aes(x = Date, y = Price, group =1)) +geom_line(color ="darkred", size =1) +labs(x ="Date", y ="Price", title ="Oil Price Over Time")# Animate the plot with gganimate, revealing the line over timeanimated_plot <- p +transition_reveal(Date)# Render the animationanimate(animated_plot, renderer = gganimate::gifski_renderer(), width =600, height =400, res =96)
3.4 Demographics
Code
demographic_data_long <- df_demographic %>%pivot_longer(cols =c('Generation Z', 'Millennials', 'Generation X', 'Baby Boomers'),names_to ="Generation",values_to ="Population" )# Plotting the data with ggplot2p_demog <-ggplot(demographic_data_long, aes(x = Year, y = Population, color = Generation)) +geom_line(size =1) +labs(title ="Demographic Trends in Switzerland",x ="Year",y ="Population") +theme_minimal() +theme(legend.position ="bottom") +scale_color_manual(values =c("Generation Z"="blue", "Millennials"="red", "Generation X"="green", "Baby Boomers"="purple"))# Convert the ggplot object to an interactive plotly objectinteractive_plot_demog <-ggplotly(p_demog, width =600, height =400)# Adjust plotly settings interactive_plot_demog <- interactive_plot_demog%>%layout(legend =list(orientation ="h", x =0, xanchor ="left", y =-0.2))# The interactive plot can be displayed in an R Markdown document or a Shiny appinteractive_plot_demog
This graph concentrates on the demographic trends’ evolution for each segment of age above mentioned throughout the time. It points out the important overall rise of individuals living in Switzerland over the past two decades.
3.5 French vehicles
3.5.1 Total vehicles evolution France
Code
# Reshape data to long formatlong_registration_data <- df_v_fr %>%select(Date, Diesel, Essence, Conventional_Hybrid, Plug_in_Hybrid, Electrique) %>%gather(key ="Fuel_Type", value ="Count", -Date)# Create ggplotp <-ggplot(long_registration_data, aes(x = Date, y =log(Count), color = Fuel_Type)) +geom_line() +scale_color_manual(values =c("Diesel"="red", "Essence"="blue", "Conventional_Hybrid"="green", "Plug_in_Hybrid"="purple", "Electrique"="orange")) +labs(x ="Date", y ="Log-Scale Count", color ="Fuel Type") +theme_minimal()# Convert to interactive plot and adjust legendggplotly(p, width =600, height =400) %>%layout(legend =list(orientation ='h', x =0.5, xanchor ='center', y =-0.15))
3.5.2 Deltas evolution
Code
# Reshape data to long formatlong_df_v_fr <- df_v_fr %>%select(Date, Diesel_delta, Essence_delta, Conventional_Hybrid_delta, Plug_in_Hybrid_delta, Electrique_delta) %>%gather(key ="Fuel_Type", value ="Delta", -Date)# Map Fuel_Type values to desired nameslong_df_v_fr$Fuel_Type <-recode(long_df_v_fr$Fuel_Type,"Diesel_delta"="Diesel","Essence_delta"="Petrol","Conventional_Hybrid_delta"="Conventional hybrid","Plug_in_Hybrid_delta"="Plug-in hybrid","Electrique_delta"="Electricity")# Create ggplotp <-ggplot(long_df_v_fr, aes(x = Date, y = Delta, color = Fuel_Type)) +geom_line(size =1) +labs(title ="Evolution of cars registered in France over the years by fuel type (Deltas)",x ="Years",y ="Value",color ="Fuel Category") +theme_minimal() +scale_color_manual(values =c("Diesel"="red", "Petrol"="blue", "Conventional hybrid"="green", "Plug-in hybrid"="purple","Electricity"="orange"))# Convert to interactive plot and adjust legendggplotly(p, width =600, height =400) %>%layout(legend =list(orientation ='h', x =0.5, xanchor ='center', y =-0.3))
3.6 Swiss vs France
3.6.1 Electric vs Hybrid vs Petrol
Here we compare and visualize specific vehicle fuel types between Swiss and French datasets.
The thicker line are the for Switzerland, the others are for France. We standardized the counts in both the Swiss and French datas ets for comparison purposes. Please juggle with the interactive plot to make it more readable.
Code
# Filtering Swiss data for specific fuel typesswiss_specific_fuel <- df_v %>%filter(Fuel %in%c("Diesel", "Electricity", "Conventional hybrid", "Plug-in hybrid", "Petrol")) %>%filter(Location =='Switzerland') |>filter(VehicleType =='Passenger car') |>filter(Date >as.Date('2012-01-01')) |>filter(Date <as.Date('2021-12-31'))# Selecting equivalent columns from the French datasetfrench_specific_fuel <- df_v_fr %>%select(Date, Diesel_delta, Essence_delta, Conventional_Hybrid_delta, Plug_in_Hybrid_delta, Electrique_delta) # Adjust column names accordingly# Reshape French dataset to long format for easier plottingfrench_specific_fuel_long <- french_specific_fuel %>%pivot_longer(cols =-Date, names_to ="Fuel", values_to ="Count")# Standardize counts in each datasetswiss_specific_fuel <- swiss_specific_fuel %>%mutate(Count =scale(Count))french_specific_fuel_long <- french_specific_fuel_long %>%mutate(Count =scale(Count))# Rename the 'Fuel' column in the French datasetfrench_specific_fuel_long <- french_specific_fuel_long %>%mutate(Fuel =case_when( Fuel =="Diesel_delta"~"Diesel", Fuel =="Essence_delta"~"Petrol", Fuel =="Conventional_Hybrid_delta"~"Conventional hybrid", Fuel =="Plug_in_Hybrid_delta"~"Plug-in hybrid", Fuel =="Electrique_delta"~"Electricity" ))# Define color palette for each fuel typefuel_colors <-c("Diesel"="black", "Electricity"="green", "Conventional hybrid"="purple", "Plug-in hybrid"="blue", "Petrol"="orange")p <-ggplot() +geom_smooth(data = swiss_specific_fuel, aes(x = Date, y = Count, color = Fuel), method ="loess", se =FALSE, size =1.5) +geom_line(data = french_specific_fuel_long, aes(x = Date, y = Count, color = Fuel), alpha =0.4, size =0.8) +scale_color_manual(values = fuel_colors, labels =c("Diesel", "Electricity", "Conventional hybrid", "Plug-in hybrid", "Petrol"),breaks =c("Diesel", "Electricity", "Conventional hybrid", "Plug-in hybrid", "Petrol")) +labs(x ="Date", y ="Standardized Count", color ="Fuel Type") +theme_minimal() +geom_text(data =data.frame(x =as.Date("2021-01-01"), y =c(3, 2.8), label =c("Switzerland has", "the thickest line")), aes(x = x, y = y, label = label, color = label), size =4, show.legend =FALSE)interactive_plot <-ggplotly(p, width =600, height =400, tooltip =c("x", "y", "color"))interactive_plot <- interactive_plot %>%layout(legend =list(orientation ="h", x =0, xanchor ="left", y =-0.2))interactive_plot
Code
# Plotting with faceting and improved axis textp <-ggplot() +geom_smooth(data = swiss_specific_fuel, aes(x = Date, y = Count, color = Fuel), method ="loess", se =FALSE, size =1.5) +geom_line(data = french_specific_fuel_long, aes(x = Date, y = Count, color = Fuel), alpha =0.4, size =0.8) +scale_color_manual(values = fuel_colors, labels =c("Switzerland", "France")) +labs(x ="Date", y ="Standardized Count") +theme_minimal() +theme(legend.position ="bottom",strip.background =element_blank(),strip.text.x =element_text(size =10, angle =0),axis.text.x =element_blank(),axis.text.y =element_blank(),axis.title.x =element_text(size =12, margin =margin(t =10)),axis.title.y =element_text(size =12, margin =margin(r =10))) +facet_wrap(~Fuel, scales ='free_y', ncol =1)# Convert to interactive plotinteractive_plot <-ggplotly(p, width =600, height =600, tooltip =c("x", "y", "color"))interactive_plot <- interactive_plot %>%layout(legend =list(orientation ="h", x =0, xanchor ="left", y =-0.2))interactive_plot
3.7 EV and Google Trends
All in all, the Google trend seems to be in adequation with the actual rise in EVs around Switzerland.
Code
df_v_electric <- df_v |>filter(VehicleType =="Passenger car") |>filter(Fuel =='Electricity')df_electric_vehicles_agg <- df_v_electric %>%group_by(Date) %>%summarize(Count =sum(Count))# Resample both datasets to a monthly frequency using the first day of the month# Merge datasetsmerged_df <-merge(df_electric_vehicles_agg, df_gtrends, by ="Date")# Calculate the ratio for the secondary axismax_values <- merged_df |>summarize(max_count =max(Count, na.rm =TRUE), max_search =max(SearchRatio, na.rm =TRUE))ratio <- max_values$max_count / max_values$max_search# Add the ratio-adjusted SearchRatio to the merged datasetmerged_df <- merged_df |>mutate(AdjustedSearchRatio = SearchRatio * ratio)# Plotting with smoothing and color changesp <-ggplot(merged_df, aes(x = Date)) +geom_bar(aes(y = AdjustedSearchRatio, fill ="Google Trends"), stat ="identity") +geom_smooth(aes(y = Count, color ="Electric Vehicles Smoothed"), method ="loess", span =0.2) +scale_y_continuous("Number of Electric Vehicles",sec.axis =sec_axis(~ . / ratio, name ="Google Trends") ) +labs(title ="Comparison of Electric Vehicle Rise and Google Trends Over Time",x ="Date", fill ="Legend", color ="Legend") +scale_fill_manual(values =c("Google Trends"="darkred")) +scale_color_manual(values =c("Electric Vehicles Smoothed"="blue")) +theme_minimal() +theme(legend.position ="bottom")# Convert to interactive plotinteractive_plot <-ggplotly(p, width =600, height =400) %>%layout(legend =list(orientation ="h", x =0.5, xanchor ="center", y =-0.3))interactive_plot
3.8 EV and Oil Price
The results of the graphic comparing oil price and EVs evolution comforts us in our choice of oil price as an explicative variable. Indeed, the tendency is quite similar since 2020. In fact, the previous years refer to a period where EVs were not as commercialized as today. Obviously, we are aware of the numerous other variables explaining both oil price and EVs rise over time.
Code
# Resample data to monthly frequency and calculate mean oil pricedf_oil_monthly <- df_oil %>%mutate(Date =as.Date(format(Date, "%Y-%m-01"))) %>%group_by(Date) %>%summarize(Price =mean(Price), .groups ='drop')# Resample electric vehicles data to monthly frequency and sum countsdf_electric_vehicles_monthly <- df_electric_vehicles_agg %>%mutate(Date =as.Date(format(Date, "%Y-%m-01"))) %>%group_by(Date) %>%summarize(Count =sum(Count), .groups ='drop')# Merge datasetsdf_merged <-full_join(df_electric_vehicles_monthly, df_oil_monthly, by ="Date")# Calculate the ratio for the secondary axismax_values <- df_merged |>summarize(max_count =max(Count, na.rm =TRUE), max_price =max(Price, na.rm =TRUE))ratio <- max_values$max_count / max_values$max_price# Add the ratio-adjusted Price to the merged datasetdf_merged <- df_merged |>mutate(AdjustedPrice = Price * ratio)# Plotting with smoothing and color changesp <-ggplot(df_merged, aes(x = Date)) +geom_smooth(aes(y = Count, color ="Electric Vehicles Smoothed"), method ="loess", span =0.2) +geom_line(aes(y = AdjustedPrice, color ="Oil Price")) +scale_y_continuous("Number of Electric Vehicles",sec.axis =sec_axis(~ . / ratio, name ="Oil Price") ) +labs(title ="Comparison of Electric Vehicle Rise and Oil Prices Over Time",x ="Date", color ="Legend") +scale_color_manual(values =c("Electric Vehicles Smoothed"="blue", "Oil Price"="darkred")) +theme_minimal() +theme(legend.position ="bottom")# Convert to interactive plotinteractive_plot <-ggplotly(p, width =600, height =400) %>%layout(legend =list(orientation ="h", x =0.5, xanchor ="center", y =-0.3))interactive_plot